package top.i51213.fastaction.uri;

import android.content.ContentValues;
import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;

import androidx.annotation.NonNull;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.WeakReference;

import top.i51213.fastaction.util.IOUtil;

public class UriWriter {
    public static final String DCIM = "DCIM",
            Movie = "Movie",
            Music = "Music",
            Pictures = "Pictures",
            Alarm = "Alarm",
            Ringtones = "Ringtones",
            Download = "Download";

    private final WeakReference<Context> context;

    private final String disPlayName;
    private final MimeType mimeType;
    private Uri uri;

    public UriWriter(Context context, String disPlayName, MimeType mimeType, boolean inner) {
        this.context = new WeakReference<>(context);
        this.disPlayName = disPlayName;
        this.mimeType = mimeType;
        if (!inner) {
            File file = new File(mimeType.getDefaultDir(), disPlayName);
            uri = Uri.fromFile(checkFile(file));
        }
        if (uri == null) {
            uri = Uri.fromFile(checkFile(IOUtil.createCacheFile(getContext(), disPlayName)));
        }
    }

    public static File checkFile(File file) {
        if (!file.exists()) return file;
        String path = IOUtil.getFilePathNoExt(file.getPath()) +"_"+ IOUtil.getRandomTime() + IOUtil.getExt(file.getName());
        return new File(path);
    }

    public Context getContext() {
        return context.get();
    }

    public String getDisPlayName() {
        return disPlayName;
    }

    public MimeType getMimeType() {
        return mimeType;
    }

    public Uri getUri() {
        return uri;
    }

    public OutputStream openOutputStream() throws IOException {
        if ("content".equals(uri.getScheme())) {
            return getContext().getContentResolver().openOutputStream(uri);
        } else if ("file".equals(uri.getScheme())) {
            return new FileOutputStream(uri.getPath());
        } else {
            throw new IOException("不支持的Uri协议");
        }
    }

    /***
     * 无法创建输出文件，暂不提供
     * @return
     * @throws IOException
     */
    private ParcelFileDescriptor.AutoCloseOutputStream openAutoCloseOutputStream() throws IOException {
        if("content".equals(uri.getScheme())){
            return new ParcelFileDescriptor.AutoCloseOutputStream(getContext().getContentResolver().openFileDescriptor(uri,"w"));
        }else if("file".equals(uri.getScheme())){
            System.out.println("open:"+uri);
            return new ParcelFileDescriptor.AutoCloseOutputStream(ParcelFileDescriptor.open(new File(uri.getPath()),ParcelFileDescriptor.MODE_CREATE));
        }else{
            throw new IOException("不支持的Uri协议");
        }
    }
    private Uri insert() {
        Uri tableUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        // 创建图片索引
        ContentValues values = new ContentValues();
        values.put(MediaStore.Images.Media.DISPLAY_NAME, disPlayName);
        values.put(MediaStore.Images.Media.MIME_TYPE, mimeType.get());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            values.put(MediaStore.Images.Media.RELATIVE_PATH, DCIM);
        }
        values.put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis());
        // 将该索引信息插入数据表，获得图片的Uri
        return getContext().getContentResolver().insert(tableUri, values);
    }

    @NonNull
    @Override
    public String toString() {
        return "UriWriter{" +
                "context=" + context +
                ", disPlayName='" + disPlayName + '\'' +
                ", mimeType=" + mimeType +
                ", uri=" + uri +
                '}';
    }
}
